package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.CommunityPostInfoActivity;
import cn.otrue.patienthealthmanager.activity.HealthyCommunityActivity;
import cn.otrue.patienthealthmanager.adapter.CommunityFragtAdpater;
import cn.otrue.patienthealthmanager.bean.ThreadModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.XListView;
import cn.otrue.patienthealthmanager.view.XListView.IXListViewListener;

import com.google.gson.reflect.TypeToken;

public class HealthyComyFragment extends BaseFragment implements
		IXListViewListener {

	private CommunityFragtAdpater poAdapter;
	private List<ThreadModel> goods;
	private View rootView;

	private int currentPage = 1;
	private XListView lv_community_par;
	private LinearLayout ll_yuan;

	private List<Map<String, String>> butt = new ArrayList<Map<String, String>>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.healthycomy_fragment, null);

		initView(rootView);
		return rootView;

	}

	private void initView(final View rootView) {

		ll_yuan = (LinearLayout) rootView.findViewById(R.id.ll_yuan);
		goods = new ArrayList<ThreadModel>();

		lv_community_par = (XListView) rootView
				.findViewById(R.id.lv_community_par);
		lv_community_par.setPullLoadEnable(false); // 是否开启上拉加载
		lv_community_par.setXListViewListener(this);// 上啦加载和下拉刷新的监听
		lv_community_par.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int threadId = goods.get(arg2 - 1).getThreadId();

				Intent intent = new Intent();
				intent.putExtra("threadId", threadId);
				intent.setClass(rootView.getContext(),
						CommunityPostInfoActivity.class);
				startActivity(intent);

			}
		});

		poAdapter = new CommunityFragtAdpater(rootView.getContext(), goods);
		lv_community_par.setAdapter(poAdapter);

		getfatie(currentPage);
		getsp();

	}

	private Handler fatieHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			onLoad();
			if (state.equals("001")) {
				String tuu = data.getString(HttpCons.DATA);
				List<ThreadModel> iiii = HttpServer.gson.fromJson(tuu,
						new TypeToken<List<ThreadModel>>() {
						}.getType());
				int uuu = goods.size();
				goods.addAll(iiii);
				if (goods.size() > 5) {
					lv_community_par.setPullLoadEnable(true);

				}
				poAdapter = new CommunityFragtAdpater(rootView.getContext(),
						goods);
				lv_community_par.setAdapter(poAdapter);
				lv_community_par.setSelection(uuu);
				Toast.makeText(rootView.getContext(), "操作成功", 0).show();
			} else {
				Toast.makeText(rootView.getContext(), msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			onLoad();
			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常
				Toast.makeText(rootView.getContext(), "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private void getfatie(int i) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		// map.put("sectionId", iii);
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername("");
		parameter.setPassword(" ");
		parameter.setCurrentPage(i + "");
		parameter.setPagesize("20");
		parameter.setData(map);
		new HttpServer().post(HttpCons.query_Thread_List, parameter,
				fatieHandler);

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		lv_community_par.setPullLoadEnable(false);
		goods.clear();
		currentPage = 1;

		getfatie(currentPage);
		super.onResume();
	}

	private void onLoad() {
		lv_community_par.stopRefresh();
		lv_community_par.stopLoadMore();
		lv_community_par.setRefreshTime("刚刚");
	}

	private Handler GHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			String tuu = data.getString(HttpCons.DATA);

			if (state.equals("001")) {
				List<Map<String, String>> Data = HttpServer.gson.fromJson(tuu,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());
				butt.addAll(Data);
				LayoutParams params = new LayoutParams(160, 160);
				params.setMargins(16, 0, 0, 0);
				ll_yuan.removeAllViews();
				LayoutInflater inflater = LayoutInflater.from(getActivity());
				for (int i = 0; i < butt.size(); i++) {

					TextView gl_er = (TextView) inflater.inflate(
							R.layout.item_yuan, null);
					gl_er.setText(butt.get(i).get("sectionName"));
					gl_er.setTag(i);

					gl_er.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							int id = Integer.parseInt(v.getTag().toString());
							// TODO Auto-generated method stub
							Intent intent = new Intent();

							intent.putExtra("sectionId",
									butt.get(id).get("sectionId"));

							intent.putExtra("sectionName",
									butt.get(id).get("sectionName"));
							intent.setClass(rootView.getContext(),
									HealthyCommunityActivity.class);
							startActivity(intent);
						}
					});
					ll_yuan.addView(gl_er, params);
				}

				Toast.makeText(rootView.getContext(), "操作成功", 0).show();
			} else {
				Toast.makeText(rootView.getContext(), "失败", 0).show();

			}
		}

		@Override
		public void onFail(Bundle data, String state) {

			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常
				Toast.makeText(rootView.getContext(), "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private void getsp() {
		HashMap<String, Object> map = new HashMap<String, Object>();

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPassword(" ");
		parameter.setData(map);
		new HttpServer().post(HttpCons.add_Module, parameter, GHandler);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onRefresh() {
		goods.clear();
		currentPage = 1;

		getfatie(currentPage);

	}

	@Override
	public void onLoadMore() {
		currentPage++;

		getfatie(currentPage);

	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			// 相当于Fragment的onResume
			if (lv_community_par != null) {
				goods.clear();
				getfatie(currentPage);

				// }
			} else {
				// 相当于Fragment的onPause

			}
		}
	}

	public static Fragment newInstance() {
		// TODO Auto-generated method stub
		return new HealthyComyFragment();
	}
}
